package com.woniuxy.auth.controller;

import com.woniuxy.auth.service.AdminService;
import com.woniuxy.commons.dto.AuthDto;
import com.woniuxy.commons.entity.Admin;
import com.woniuxy.commons.entity.User;
import com.woniuxy.commons.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: 王敞
 * @E-mail： 365799712@qq.com
 * @Date: 2020/07/29/11:01
 * @Description:
 */
@RestController
public class AuthController {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private AdminService adminService;

    @PostMapping("/login")
    public AuthDto login(Admin admin) {
        // 去数据库搜索账号密码来进行验证
        Admin admin1 = adminService.findAdminByAName(admin.getAname());
        if (admin1 == null) {
            return new AuthDto().setCode(330).setMessage("账号或密码错误");
        }
        if (!admin.getPwd().equals(admin1.getPwd())) {
            return new AuthDto().setCode(330).setMessage("账号或密码错误");
        }
        // 生成token，refreshToken
        String refreshToken = UUID.randomUUID().toString();

        String token = JwtUtil.makeToken(admin.getAname());
        // 将token，refreshToken存放到redis
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("token", token);
        map.put("uname", admin.getAname());
        // 放入redis，同时设置refreshtoken的过期时间
        redisTemplate.opsForHash().putAll(refreshToken, map);
        // 同时设置refreshtoken的过期时间
        redisTemplate.expire(refreshToken, JwtUtil.REFRESH_TOKEN_EXPRE_TIME, TimeUnit.MILLISECONDS);
        // 将token、refreshtoken返回给浏览器
        AuthDto authDto = new AuthDto().setCode(200).setMessage("认证成功").setRefreshToken(refreshToken).setToken(token);
        return authDto;
    }

    /**
     * 刷新token，生成新的token
     *
     * @param refreshToken
     * @return
     * @author 王敞
     */
    @PostMapping("/refresh/{refreshToken}")
    public AuthDto refresh(@PathVariable("refreshToken") String refreshToken) {
        Map<Object, Object> data = redisTemplate.opsForHash().entries(refreshToken);
        String uname = (String) data.get("uname");
        String token = JwtUtil.makeToken(uname);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("token", token);
        map.put("uname", uname);
        // 放入redis
        redisTemplate.opsForHash().putAll(refreshToken, map);
        AuthDto authDto = new AuthDto().setCode(200).setMessage("刷新成功").setRefreshToken(refreshToken).setToken(token);
        return authDto;
    }
}
